package tech.runchen.gz5055.oms.common.utils.poi;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.compress.utils.Lists;
import tech.runchen.gz5055.oms.common.constant.Constant;
import tech.runchen.gz5055.oms.modules.system.service.IExcelImportService;

import java.util.List;

/**
 * @author zzj
 */
public class ExcelImportDataListener<T> extends AnalysisEventListener<T> {

    private IExcelImportService service;
    private List<T> dataList = Lists.newArrayList();

    public ExcelImportDataListener(IExcelImportService service) {
        this.service = service;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        dataList.add(t);
        // 可以设置超过500条了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (dataList.size() >= Constant.EXCEL_IMPORT_MAX) {
            saveBatchData();
            // 存储完成清理 list
            dataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveBatchData();
    }

    private void saveBatchData() {
        service.batchImportData(dataList);
    }
}
